define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'note/day/index' + location.search,
                    // add_url: 'note/day/add',
                    edit_url: 'note/day/edit',
                    // del_url: 'note/day/del',
                    multi_url: 'note/day/multi',
                    import_url: 'note/day/import',
                    table: 'note_day',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                // sortName: 'date_time',
	            // sortOrder: 'asc',
	            sortName:'date_time asc,update_time desc',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), operate: false, visible: false},
	                    {field: 'scene_id', title: __('场景'), visible: false},
	                    {field: 'contact.name', title: '姓名', operate: 'LIKE'},
	                    {field: 'user.phone', title: '手机号', operate: 'LIKE'},
	                    {field: 'customer.name', title: '客户', operate: "LIKE",
		                    align: 'left',
		                    customField: 'tags',
		                    formatter: function (value, row, index) {
		                        if(row.customer_id==0) return '-';
		                        value='<a href="javascript:void(0);" data-url="facrm/customer/index/detail/ids/' + row.customer_id
		                            +'" data-area="[&quot;98%&quot;,&quot;98%&quot;]" class="btn-dialog" data-title="'+ row.customer.name+'">'+ row.customer.name +'('+row.customer_id+')'+'</a>';
		                        return value;
		                    }
						},
                        // {field: 'week_id', title: __('Week_id')},
                        // {field: 'uid', title: __('Uid')},
                        // {field: 'customer_id', title: __('Customer_id')},
                        // {field: 'contact_id', title: __('Contact_id')},
                        {field: 'week_day', title: __('Week_day'), searchList: {"0":__('Week_day 0'),"1":__('Week_day 1'),"2":__('Week_day 2'),"3":__('Week_day 3'),"4":__('Week_day 4'),"5":__('Week_day 5'),"6":__('Week_day 6')}, formatter: Table.api.formatter.normal},
                        // {field: 'date_time', title: __('Date_time'), operate:false, addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'date_text', title: __('Date_text'), operate:false, addclass:'datetimerange', autocomplete:false},
	                    {field: 'tasks' ,width: '300px', title: __('任务'), operate:false, formatter : function (value, row, index) {
								var content = '<ul>';
								$.each(value, function(i,o){
									content += '<li>'+o.content+'</li>';
								})
								content += '</ul>';
								return content;
		                    }},
                        {field: 'notice', title: __('Notice'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'feeling', title: __('Feeling'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
	                    {field: 'ai_reply', title: __('Ai_reply'), operate: false, table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'ai_reply_time', title: __('Ai_reply_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate
							,buttons:[
                                {
                                    name: 'edit',
	                                extend: 'data-area=\'["80%","80%"]\''
                                },
                            ]
						}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
			Controller.api.print_list(table)
        },
	    user: function (){
			this.index();
	    },
        add: function () {
            Controller.api.bindevent();
			Controller.api.print();
        },
        edit: function () {
            Controller.api.bindevent();
			Controller.api.print_single();
			Controller.api.ai();
        },
        api: {
            bindevent: function () {
				 //监听文本框改变事件
                $(document).on('change', ".cycle_type", function () {
					let cycle_type = $(this).val();
					let index = $(this).index('.cycle_type');
					$('.cycle_line:eq('+index+') .plus_select').hide();
					$('.cycle_line:eq('+index+') .cycle_days').val('')
	                $('[name=cycle_week_sel]:eq('+index+')').val(0)
	                $('[name=cycle_month_sel]:eq('+index+')').val(0)
	                $('.selectpicker', $('#edit-form')).selectpicker('refresh');
					$('.cycle_line:eq('+index+') .cycle_end_date').show()

					switch(cycle_type) {
						case '1':
							break;
						case '2':
							$('.cycle_line:eq('+index+') .cycle_week').show()
							break;
						case '3':
							$('.cycle_line:eq('+index+') .cycle_month').show()
							break;
						default:
							$('.cycle_line:eq('+index+') .cycle_end_date').hide()
							break;
					}
                });

				$(document).on('change', "[name=cycle_week_sel],[name=cycle_month_sel]", function () {
					let name = $(this).attr('name')
					let index = $(this).index('[name='+name+']');
					$('.cycle_line:eq('+index+') .cycle_days').val($(this).val());
				})

				$(document).on("fa.event.appendfieldlist", '.btn-append', function(obj,html){
	                //通用的表单组件事件绑定和组件渲染
					var week = $('[name=cycle_week_sel]').last();
					if(week.length>0) week.val(week.data('val').split(','));
					var month = $('[name=cycle_month_sel]').last();
					if(month.length>0) month.val(month.data('val').split(','));
	                setTimeout(function () {
						$('.selectpicker', $('#edit-form')).selectpicker('refresh');
	                },1)
					Form.events.datetimepicker($("#edit-form"));
	            });

                Form.api.bindevent($("form[role=form]"));
            },
	        ai: function(){
				$('#ai').click(function(){
					if($('#c-notice').val()!='' || $('#c-notice').val()!=''){
						Form.api.submit($("form[role=form]"),function(){
							window.location.reload();
						})
					}else{
						Toastr.error('请填写察觉或感受');
					}
				})
	        },
	        print_list: function(table){
				$('#print').click(function(){
					let selected = Table.api.selecteddata(table)
					let datas = [];
					$.each(selected, function(i,o){
						datas.push({
							name : o.contact.name,
							date : o.date_text,
							okrs : o.okrs,
							tasks : o.tasks,
							notice : o.notice,
							feeling : o.feeling,
							ai_reply : o.ai_reply,
						});
					})
					Controller.api.print_page(datas)
				})
	        },
	        print_single: function() {
				$('#print').click(function(){
					Form.api.submit($("form[role=form]"),(form, data, ret)=>{
						const datas = [
							{
								name : $('#contact_name').val(),
								date : data.data.date_text,
								okrs : JSON.parse($('[name="okr"]').val()),
								tasks : JSON.parse($('[name="task"]').val()),
								notice : $('[name="row[notice]"]').val(),
								feeling : $('[name="row[feeling]"]').val(),
								ai_reply : data.data.ai_reply,
							}
						];
						Controller.api.print_page(datas)
					})
				})
	        },
	        print_page: function(data){
				$('#print-box').remove();
				let temps = '';
				$.each(data, function(i,o){
					temps += Controller.api.print_temp(o.name,o.date,o.okrs,o.tasks);
					if(i<data.length-1) temps += '<div class="page-break"></div>';
				})
				let html = '<div id="print-box">' + temps + '</div>';
				$('.content').append(html);
				Controller.api.print_do();
	        },
	        print_temp: function(name,date,okrs,tasks){
				let okr_html = '';
				$.each(okrs, function(i,o){
					var text_decoration= o.status == '1' ? 'line-through' : 'none';
					okr_html += '<li style="text-decoration:'+text_decoration+'">'+o.content+'</li>';
				})

				let task_html = '';
				$.each(tasks, function(i,o){
					var text_decoration= o.status == '1' ? 'line-through' : 'none';
					task_html += '<li style="text-decoration:'+text_decoration+'">'+o.content+'</li>';
				})

				let temp = `<div class="header">` +
									`<p class="title">任务清单</p>` +
									`<p>[ 新知识固化过程管理 ]</p>` +
								`</div>` +
								`<div class="main">` +
									`<div class="user-info">` +
										`姓名：<span>`+name+`</span>&nbsp;` +
										`日期：<span>`+date+`</span>&nbsp;` +
									`</div>` +
									`<div class="list">` +
										`<p>本周目标</p>` +
										`<ul>`+okr_html+`</ul>` +
									`</div>` +
									`<div class="list">` +
										`<p>今天记忆复习清单</p>` +
										`<ul>`+task_html+`</ul>` +
									`</div>` +
									/*`<div class="text-context-box">` +
										`<p>察觉：</p>` +
										`<div class="text-context" id="notice"></div>` +
									`</div>` +
									`<div class="text-context-box">` +
										`<p>感受：</p>` +
										`<div class="text-context" id="feeling"></div>` +
									`</div>` +
									`<div class="text-context-box">` +
										`<p>AI反馈：</p>` +
										`<div class="text-context" id="ai"></div>` +
									`</div>` +*/
									`<div class="text">` +
										`<p>---完成后请在后侧打勾---</p>` +
										`<p>---本小票需要保存到学习记录中---</p>` +
									`</div>` +
								`</div>` +
								`<div class="footer">` +
									`<p>文心一格 · 潜龙觉</p>` +
									`<p>潜意识学习力密训营</p>` +
								`</div>`
		        return temp;
	        },
	        print_do: function() {
				if (!!window.ActiveXObject || "ActiveXObject" in window) {
					Controller.api.remove_ie_header_and_footer();
				}
				window.print();
			},
	        remove_ie_header_and_footer: function() {
				var hkey_root, hkey_path, hkey_key;
				hkey_path = "HKEY_CURRENT_USER\\Software\\Microsoft\\Internet Explorer\\PageSetup\\";
				try {
					var RegWsh = new ActiveXObject("WScript.Shell");
					RegWsh.RegWrite(hkey_path + "header", "");
					RegWsh.RegWrite(hkey_path + "footer", "");
				} catch (e) {}
			}
        }
    };
    return Controller;
});
